<template>
  <a-card :bordered='false'>
    <search :config='searchConfig' @search='search' @getHeight='getHeight' />
    <!-- table区域-begin -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        :border='true'
        :resizable='true'
        :showOverflow='true'
        size='mini'
        :loading='loading'
        :height='pageHeight-seachHeight-90'
        :align='left'
        :columns='columns'
        :data='dataSource'
        :toolbar-config='tableToolbar'
        :checkbox-config='checkboxConfig'
        v-bind='vexConfig'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button @click='handleAdd' v-has="'terminal:add'" type='primary'>新增</a-button>
            <a-button tabindex='primary' @click='batchDel'>删除</a-button>
            <a-button type='primary' @click="handleExportXls('终端管理')">模板下载</a-button>
            <a-upload name='file' :showUploadList='false' :multiple='false' :headers='tokenHeader1'
                      :action='importExcelUrl' @change='handleImportExcel'>
              <a-button type='primary'>导入</a-button>
            </a-upload>
            <a-button type='primary' v-has="'terminal:export'" @click="downExportXls('terminal_service')">导出</a-button>
            <a-button type='primary' @click="handleExportXls('职位管理')">门店职位关系模板下载</a-button>
            <a-upload name='file' :showUploadList='false' :multiple='false' :headers='tokenHeader1'
                      :action='importExcelUrl2' @change='handleImportExcel'>
              <a-button type='primary'>门店职位关系导入</a-button>
            </a-upload>

            <!-- <a-button type='primary' v-has="'terminal:export'" @click="downExportXls('terminal_service')">门店职位关系导出</a-button> -->
          </div>
        </template>

        <template #avatarslot='{ row }'>
          <viewer :images='[row.avatar]'>
            <a-avatar shape='square' size='small' :src='row.avatar' icon='user' />
          </viewer>
        </template>
        <template #status='{ row,rowIndex }'>
          <a-switch :checked='row.status' size='small' @change='handleStatus(row,$event)' />
        </template>
        <template #detail='{ row,rowIndex }'>
          <a @click='handleDetail(row)'>{{ row.terminalCode }}</a>
        </template>
        <template #isLeader='{ row }'>
          {{ row.isLeader == 0 ? '是' : '否' }}
        </template>
        <div slot='isActiveStatus' slot-scope='text,recode'>
          {{ text|isActiveStatus }}
        </div>
        <div slot='filterTerminalType' slot-scope='text,recode'>
          {{ text|filterTerminalType }}
        </div>

        <template #action='{ row:record }'>
          <a v-has="'terminal:update'" @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a-dropdown>
            <a class='ant-dropdown-link'>更多
              <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a href='javascript:' @click='handleConfigTer(record)'>门店配置</a>
              </a-menu-item>
              <a-menu-item v-has="'business:log'">
                <a href='javascript:' @click='handleBusiness("门店管理",record)'>日志</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>

        <template #pager>
          <vxe-pager :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
                     :currentPage.sync='ipagination.current' :page-size.sync='ipagination.pageSize'
                     :total='ipagination.total'
                     :pageSizes='ipagination.pageSizeOptions' @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <terminal-modal ref='modalForm' @ok='modalFormOk'></terminal-modal>

    <WhiteModal modal-width='90%' ref='WhiteModal' @ok='handelSaveWhite'></WhiteModal>

    <config-pos-cust ref='ConfigPosCust' @ok='savePosCust'></config-pos-cust>
    <business-log ref="businessLog"></business-log>

  </a-card>
</template>

<script>
import WhiteModal from './modules/WhiteModal'
import { postAction, getFileAccessHttpUrl, getAction, downFile } from '@/api/manage'
import terminalModal from './modules/TerminalModal'
import stockModal from './modules/stockModal'
import uploadExcel from '@/components/upload-file/UploadExcel.vue'
import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import ConfigPosCust from './modules/TerPosCustConfigModal'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'terminal-list',
  mixins: [PageListMixin],
  components: {
    uploadExcel,
    terminalModal,
    stockModal,
    WhiteModal,
    ConfigPosCust
  },
  data() {

    return {
      tokenHeader1: { 'Authorization': 'Bearer ' + Vue.ls.get(ACCESS_TOKEN).access_token },
      description: '门店列表',
      searchConfig: [{
        type: 'input',
        name: 'terminalCode',
        placeholder: '门店编码'
      },
        {
          type: 'input',
          name: 'terminalName',
          placeholder: '门店名称'
        },
        // {
        //   type: 'j-select',
        //   dictCode: 'term_channel',
        //   name: 'channel',
        //   placeholder: '渠道类型'
        // },
        {
          type: 'j-select',
          dictCode: 'terminal_level',
          name: 'terminalLevel',
          placeholder: '门店等级'
        },
        {
          type: 'tree-select',
          dataType: 'org',
          name: 'orgCode',
          placeholder: '组织'
        },
        {
          type: 'input',
          name: 'custName',
          placeholder: '客户'
        },
        {
          type: 'input',
          name: 'businessLicense',
          placeholder: '营业执照'
        }
      ],
      //字典数组缓存
      sexDictOptions: [],
      //列定义
      columns: [{
        type: 'checkbox',
        minWidth: 60,
        fixed: 'left'
      },
        {
          title: '门店编码',
          field: 'terminalCode',
          minWidth: 100,
          fixed: 'left',
          slots: { default: 'detail' }
        },
        {
          title: '门店名称',
          minWidth: 80,
          field: 'terminalName'
        },
        {
          title: '门店类型',
          minWidth: 80,
          field: 'terminalType_dictText'
        },
        {
          title: '门店等级',
          minWidth: 80,
          field: 'terminalLevel_dictText'
        },
        {
          title: '所属组织',
          minWidth: 80,
          field: 'orgName'
        },
        {
          title: '客户名称',
          minWidth: 80,
          field: 'custName'
        },
        {
          title: '省',
          minWidth: 80,
          field: 'province'
        },
        {
          title: '市',
          minWidth: 80,
          field: 'city'
        },
        {
          title: '区',
          minWidth: 80,
          field: 'area'
        },
        // {
        //   title: '营业执照',
        //   minWidth: 80,
        //   field: 'businessLicense'
        // },
        {
          title: '营业执照代码',
          minWidth: 100,
          field: 'businessLicense'
        },
        {
          title: '创建人',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          minWidth: 80,
          field: 'createTime'
        },
        {
          title: '更新人',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          minWidth: 80,
          field: 'updateTime'
        },
        {
          title: '状态',
          align: 'left',
          field: 'status',
          width: 80,
          fixed: 'right',
          minWidth: 80,
          slots: { default: 'status' }
        },
        {
          title: '操作',
          fixed: 'right',
          minWidth: 120,
          field: 'action',
          slots: {
            default: 'action'
          }
        }
      ],
      url: {
        list: window._CONFIG['domianURL'] + '/cnTerminalController/custFindTerminalList',
        delete: window._CONFIG['domianURL'] + '/cnTerminalController/deleteByid',
        detail: window._CONFIG['domianURL'] + '/cnTerminalController/getCnTerminalByIdOrTerminalCode',
        deleteBatch: '/cnTerminalController/deleteBatch',
        deleteTag: window._CONFIG['domianURL'] + '/cnTerminalController/deleteLabels',
        saveOrUpdateTag: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateLabels',
        savePosCust: window._CONFIG['domianURL'] + '/cnTerminalExtendController/saveTerminalExtend',
        startOrStopUrl: window._CONFIG['domianURL'] + '/cnTerminalController/startOrStop',
        exportXlsUrl: window._CONFIG['domianURL'] + '/cnTerminalController/exportXls',
        exportXlsUrl2: window._CONFIG['domianURL'] + '/cnTerminalController/exportPostXls',
        importExcelUrl: window._CONFIG['domianURL'] + '/cnTerminalController/importExcel',
        importExcelUrl2: window._CONFIG['domianURL'] + '/cnTerminalController/importPosExcel'
      },
      isorter: {
        // userType: 1,
        permflag: 'termianl_page_impl'
      },
      currentWhite: {}
    }
  },

  computed: {
    importExcelUrl: function() {
      return `${this.url.importExcelUrl}`
    },
    importExcelUrl2: function() {
      return `${this.url.importExcelUrl2}`
    }
  },

  methods: {
    handleExportXls(fileName) {
      // if (!fileName || typeof fileName != 'string') {
      //   fileName = '导出文件'
      // }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      if(fileName=='终端管理'){
        downFile(this.url.exportXlsUrl, param).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      }
      if(fileName=='职位管理'){
        downFile(this.url.exportXlsUrl2, param).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      }
    },
    handleDetail: async function (record) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id, terminalCode: record.terminalCode })
        if (res.success) {
          if (res.result) {
            record = res.result
            console.log(record)
          }
        } else {
          this.$message.error(res.message)
        }
      }
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.edit(record)
    },
    handleEdit: async function(record) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id, terminalCode: record.terminalCode })
        if (res.success) {
          if (res.result) {
            record = res.result
            console.log(record)
          }
        } else {
          this.$message.error(res.message)
        }
      }
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.edit(record)
    },

    handleConfigTer(record, type, modal = 'ConfigPosCust') {
      this.$refs[modal].showModal(record)
      return false
    },

    async handleWhite(record) {
      this.currentWhite = record
      this.$refs.WhiteModal.showModal(record.terminalCode)
    },
    savePosCust(params) {
      postAction(this.url.savePosCust, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigPosCust.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigPosCust.confirmLoading = false
        //that.close();
      })
    },
    handelSaveWhite(typeList, productList, positionList, record) {
      let that = this
      const tList = typeList.map(type => Object.assign({
        code: type.code,
        name: type.name,
        dataType: 3
      }))
      const pList = productList.map(type => Object.assign({
        code: type.code,
        name: type.name,
        remarks: type.imgUrl,
        dataType: 4
      }))
      const positions = positionList.map(type => Object.assign({
        code: type.positionCode,
        name: type.positionName,
        dataType: 5
      }))
      if (!record.extendVos) record.extendVos = []
      const retainRows = record.extendVos.filter(row => [1, 2].includes(Number(row.dataType)))
      record.extendVos = [...retainRows, ...tList, ...pList, ...positions]
      that.loadData()
      postAction(window._CONFIG['domianURL'] + '/cnTerminalController/saveTerExtend', record).then(async (res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.$refs.WhiteModal.showModal('')
          this.$refs.WhiteModal.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.WhiteModal.confirmLoading = false
        //that.close();
      })
    },
    async handleStock(record) {
      const modal = this.$refs.stockModalForm
      modal.edit(record)
      modal.title = '详情'
      modal.disableSubmit = true
      return true
    },
    postAction,
    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    initDictConfig() {
      console.log('--我才是真的方法!--')
      //初始化字典 - 性别
      initDictOptions('sex').then((res) => {
        if (res.success) {
          this.sexDictOptions = res.result
        }
      })
    },
    //跳转单据页面
    jump() {
      this.$notification.success('跳转 ： jump')
    },
    onBirthdayChange: function(value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.birthday_begin = dateString[0]
      this.queryParam.birthday_end = dateString[1]
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.field == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.field)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.field)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (colSettings.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    // 编辑


    // 上传

    handleUploadFile: function() {
      this.$refs.uploadFile.add()
      // this.$refs.uploadFile.title = "上传";
      this.$refs.uploadFile.disableSubmit = false
    }
  },
  created() {
    this.initColumns()
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
